package com.oo.simpleimage;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * Created by zhuxiaolong on 2017/12/28.
 */

public class SimpleImageView extends View {
    private final String TAG = getClass().getSimpleName();

    public SimpleImageView(Context context) {
        this(context, null);
    }

    public SimpleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SimpleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        propertyInit(context, attrs, defStyleAttr);
    }

    private void propertyInit(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray array = context.getTheme()
                .obtainStyledAttributes(attrs, R.styleable.SimpleImageView, 0, 0);
        //轮廓线颜色
        lineColor = array.getColor(R.styleable.SimpleImageView_line_Color, Color.WHITE);
        //覆盖层颜色
        overLayColor = array.getColor(R.styleable.SimpleImageView_overlay_Color, Color.WHITE);
        // 轮廓形状
        type = array.getInteger(R.styleable.SimpleImageView_tailor_type, OUTLINE_SHAPE_DEFULT);
        //轮廓线宽
        lineWidth = array.getDimensionPixelOffset(R.styleable.SimpleImageView_line_width, 0);
        array.recycle();

        //初始化 画笔
        bitmapPaint = new Paint();
        outlinePaint = new Paint();
        overlayPaint = new Paint();
        //设置颜色
        outlinePaint.setColor(lineColor);
        overlayPaint.setColor(overLayColor);
        //设置尺寸
        outlinePaint.setStrokeWidth(lineWidth);

        //开启抗锯齿
        bitmapPaint.setAntiAlias(true);
        outlinePaint.setAntiAlias(true);
        overlayPaint.setAntiAlias(true);

    }

    /*常量*/
    /* 默认 */
    public static final int OUTLINE_SHAPE_DEFULT = 0;
    /* 圆形轮廓 */
    public static final int OUTLINE_SHAPE_CIRCLE = 1;
    /* 矩形轮廓 */
    public static final int OUTLINE_SHAPE_RECT = 2;
    /* 圆角矩形轮廓 */
    public static final int OUTLINE_SHAPE_ROUNT_RECT = 3;


    /*属性 */
    /**
     * 轮廓线宽
     */
    private float lineWidth;
    /**
     * 轮廓线颜色
     */
    private int lineColor = Color.WHITE;
    /**
     * 覆盖层 颜色
     */
    private int overLayColor = Color.WHITE;
    /**
     * 圆角 半径
     */
    private float roundRadius = 0;
    /**
     * 圆形半径
     */
    private float circleRadius = 0;
    /**
     * 轮廓 type
     */
    private int type;
    /**持有对象*/
    /**
     * bitmap
     */
    private Bitmap bitmap;

    /**
     * 绘制区域
     */
    private RectF drawRect;

    /**画笔*/
    /**
     * 图片画笔
     */
    private Paint bitmapPaint;
    /**
     * 轮廓画笔
     */
    private Paint outlinePaint;
    /**
     * 覆盖层 画笔
     */
    private Paint overlayPaint;
    //
    private Shader bitmapShader;
    private Shader overlayShader;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // Try for a width based on our minimum
        int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
        int w = resolveSizeAndState(minw, widthMeasureSpec, 1);
        // Whatever the width ends up being, ask for a height that would let the pie
        // get as big as it can
        int minh = MeasureSpec.getSize(w) + getPaddingBottom() + getPaddingTop();
        int h = resolveSizeAndState(MeasureSpec.getSize(w), heightMeasureSpec, 0);
        setMeasuredDimension(w, h);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);


        float l = getPaddingLeft();
        float t = getPaddingTop();
        float r = w - getPaddingRight();
        float b = h - getPaddingBottom();
        //记录 绘制范围  考虑轮廓线的宽
        drawRect = new RectF(l, t, r, b);
        circleRadius = Math.min(drawRect.width(), drawRect.height()) * 0.5f;
        Log.i(TAG, "onSizeChanged: drawRect : " + drawRect.toString());

        //根据参数 设置 覆盖层的 shader
        overlayShader = new SweepGradient(drawRect.centerX(), drawRect.centerY(), overLayColor, overLayColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.i(TAG, "onDraw: ");
        //绘制 bitmap
        //绘制 overlay
        drawOverlay(canvas);
        if (bitmap != null) {
            drawImage(canvas);
        }
        drawOutline(canvas);
    }


    private void drawOutline(Canvas canvas) {
        switch (type) {
            case OUTLINE_SHAPE_DEFULT:
                break;
            case OUTLINE_SHAPE_CIRCLE:
                outlinePaint.setStyle(Paint.Style.STROKE);
                //绘制 轮廓线 紧贴 drawrect 圆的半径应该是 drawrect-linewidth*0.5
                if (outlinePaint.getStrokeWidth() != 0) {
                    canvas.drawCircle(drawRect.centerX(), drawRect.centerY(),
                            circleRadius - outlinePaint.getStrokeWidth() * 0.5f, outlinePaint);
                }
                break;
            case OUTLINE_SHAPE_RECT:
                break;
            case OUTLINE_SHAPE_ROUNT_RECT:
                break;
            default:
                break;
        }

    }

    private void drawOverlay(Canvas canvas) {
        //先绘制颜色 再覆盖 outline
        canvas.drawRect(drawRect, overlayPaint);


    }

    private void drawImage(Canvas canvas) {
        Log.i(TAG, "drawImage: ");
        Matrix matrix = new Matrix();
        float sx = drawRect.width() / bitmap.getWidth();
        float sy = drawRect.height() / bitmap.getHeight();
        matrix.setScale(sx, sy);
        switch (type) {
            case OUTLINE_SHAPE_DEFULT:
                //默认  直接绘制 bitmap
                //计算缩放
//                Matrix matrix = new Matrix();
//                float sx = drawRect.width() / bitmap.getWidth();
//                float sy = drawRect.height() / bitmap.getHeight();
//                matrix.setScale(sx, sy);

                Log.i(TAG, "drawImage: default");
                canvas.drawBitmap(bitmap, matrix, bitmapPaint);
                break;
            case OUTLINE_SHAPE_CIRCLE:
                Log.i(TAG, "drawImage: circle cx=" + drawRect.centerX() + " cy = " + drawRect.centerY() + " radius = " + circleRadius);
                bitmapShader = new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
                bitmapShader.setLocalMatrix(matrix);
                bitmapPaint.setShader(bitmapShader);

                canvas.drawCircle(drawRect.centerX(), drawRect.centerY(), circleRadius, bitmapPaint);
                break;
            case OUTLINE_SHAPE_RECT:
                break;
            case OUTLINE_SHAPE_ROUNT_RECT:
                break;
            default:
                break;
        }


    }

    /**
     * 负责将目标图片进行裁剪 主要是轮廓形状
     * 如裁剪圆形、矩形、圆角矩形等。
     */
    private void tailorImage(Bitmap bitmap) {

        invalidate();
    }

    public void setImageRes(int resId) {
        bitmap = BitmapFactory.decodeResource(getResources(), resId);
        setImageBitmap(bitmap);
    }


    public void setImageBitmap(Bitmap bitmap) {
        bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        invalidate();
    }

    public void setImagePath(String path) {

    }

    /**
     * 这里要优化为 异步加载？
     */
    public void setImageUrl() {

    }


}
